/**
 * Reply for BADS Assignment 04
 * @author Michael Valentin (mier@itu.dk) and Jens Møllerhøj (jdmo@itu.dk)
 */
public class NewWar {
    public static void main(String[] args){
        NewWar w = new NewWar();
    }

    private Queue<Integer> a = new Queue<Integer>();
    private Queue<Integer> b = new Queue<Integer>();
    private Queue<Integer> table = new Queue<Integer>();
    private int rounds = 0;
    private boolean war = false;

    public NewWar()
    {
        //Deal cards (Must for some reason be dealt backwards..)
        Stack<Integer> sa = new Stack<Integer>();
        Stack<Integer> sb = new Stack<Integer>();
        int count = StdIn.readInt();
        for(int i = 0; i<count; i++){
            sa.push(this.getValue(StdIn.readString()));
        }
        for(int i = 0; i<count; i++){
            sb.push(this.getValue(StdIn.readString()));
        }
        for(int i = 0; i<count; i++){
            a.enqueue(sa.pop());
            b.enqueue(sb.pop());
        }

        //Play game
        while(!a.isEmpty() && !b.isEmpty() && rounds<100000) this.play();
        
        if(rounds<100000 && b.isEmpty())
            StdOut.println("A wins after "+rounds+" steps.");
        else if (rounds < 100000)
            StdOut.println("B wins after "+rounds+" steps.");
        else
            StdOut.println("It's a tie after 100.000 steps");
    }

    //Play the next cards from the top.
    private void play()
    {
        if(a.isEmpty() || b.isEmpty()) return;

        rounds++;

        int val_a = a.dequeue();
        int val_b = b.dequeue();
        table.enqueue(val_a);
        table.enqueue(val_b);

        //If there is a war, wait one round eg. deal two cards per player..
        if(war){
            war = false;
            return;
        }

        //Decide who wins, or if there is a war..
        if(val_a > val_b)
            while(!table.isEmpty())
                a.enqueue(table.dequeue());
        else if(val_a < val_b)
            while(!table.isEmpty())
                b.enqueue(table.dequeue());
        else
            war = true;
    }

    //Import method; convert string to number for easier (and faster) comparison..
    private int getValue(String in)
    {
        String val = in.substring(0,1);
        if(val.equals("A")){
            return 1;
        }else if(val.equals("T")){
            return 10;
        }else if(val.equals("J")){
            return 11;
        }else if(val.equals("Q")){
            return 12;
        }else if(val.equals("K")){
            return 13;
        }else{
            return Integer.parseInt(val);
        }
    }
}
